<script setup>
// defineProps：获取父组件传递的参数 defineEmits：获取父组件传递的函数  defineExpose：向父组件暴露的方法
import { ref } from "vue";
import { useMessage } from "naive-ui";
// 消息提示
const message = useMessage();

// 获取父组件传递的参数
const props = defineProps({
  // 弹窗开启 必传
  showModal: Boolean,
  // 更新数据 非必传
  updateObj: Object | null,
  // 1、新增，2、修改 必传
  type: Number,
  // 父节点节点id
  parentId: Number | String,
});
// 获取父组件传递的函数
const emit = defineEmits(["addClose", "addOpen"]);

// 父节点选择数组
const parentNodeArr = ref([]);

// 新增节点
// 创建一个表格的 ref 对象 用来验证表格数据是否填写
const formRef = ref(null);
const formData = ref({
  // 节点标题
  title: "",
  // 创建更新时间
  time: "",
  // 进度
  num: null,
  // 姓名
  name: "",
  // 节点等级 1、个人 0、公司
  level: 1,
  // 父节点id
  parentId: null,
  // 子任务数组
  taskArr: [],
  // 子任务是否关闭
  closed: false,
  // 子节点是否关闭
  nodeClosed: true,
});

// 子组件暴露给父组件的方法，修改时给formData赋值 新增不调用
const updateForm = () => {
  // 获取所有节点数据作为选择父节点
  let addNodeArrJson = localStorage.getItem("addNodeArr");
  if (addNodeArrJson) {
    addNodeArrJson = JSON.parse(addNodeArrJson);
  } else {
    addNodeArrJson = [];
  }
  parentNodeArr.value = [];
  addNodeArrJson.forEach((item) => {
    let obj = {
      label: item.data.title,
      value: item.id,
    };
    parentNodeArr.value.push(obj);
  });

  // 因为新增时不需要赋值
  if (props.updateObj) {
    formData.value = props.updateObj;
  }
  if (props.parentId) {
    formData.value.parentId = props.parentId;
  }
};
// 暴露出去，父组件通过获取子组件Dom元素获取此方法
defineExpose({ updateForm });

// 表单验证
const rules = {
  title: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入标题",
  },
  num: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入进度",
  },
  name: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入姓名",
  },
};

// 取消保存
const addClose = () => {
  formData.value = {
    title: "",
    time: "",
    num: null,
    name: "",
    level: 1,
    parentId: null,
    taskArr: [],
    closed: false,
    nodeClosed: true,
  };
  // 弹窗关闭
  emit("addClose");
};
// 新增修改弹窗
const addOpen = () => {
  // 表单验证
  formRef.value?.validate((errors) => {
    if (!errors) {
      // 添加时间
      formData.value.time = new Date().toLocaleString().replace(/\//g, "-");
      // 调用父组件新增修改函数
      emit("addOpen", formData.value, props.type);
      // 关闭弹窗
      addClose();
    } else {
      // 错误提示
      errors.forEach((item) => {
        message.error(item[0].message);
      });
    }
  });
};

// 新增子任务对象
const taskObj = ref({
  id: null,
  title: "",
  num: null,
});
// 新增子任务
const addTask = () => {
  if (taskObj.value.title && taskObj.value.num) {
    taskObj.value.id = new Date().getTime();
    formData.value.taskArr.push(taskObj.value);
    taskObj.value = {
      id: null,
      title: "",
      num: null,
    };
  } else {
    message.error("请输入子任务标题和进度");
  }
};
// 删除子任务
const delTask = (id) => {
  formData.value.taskArr = formData.value.taskArr.filter(
    (item) => item.id !== id
  );
};
</script>

<template>
  <div>
    <!-- 新建弹窗 -->
    <n-modal :show="props.showModal" @maskClick="addClose">
      <div
        style="
          background-color: white;
          padding: 16px 12px;
          width: 500px;
          border-radius: 10px;
        "
      >
        <div style="display: flex; align-items: center">
          <span
            style="margin-right: 50px; font-size: 18px; font-weight: bold"
            >{{ type == 1 ? "新增" : "修改" }}</span
          >
          <n-button type="primary" :text="true" @click="addClose"
            >关闭</n-button
          >
        </div>
        <n-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-placement="left"
          label-width="auto"
          require-mark-placement="right-hanging"
          style="margin-top: 20px"
        >
          <n-form-item label="标题" path="title">
            <n-input v-model:value="formData.title" placeholder="请输入标题" />
          </n-form-item>
          <n-form-item label="进度" path="num">
            <n-input
              type="number"
              v-model:value="formData.num"
              placeholder="请输入进度"
            />
          </n-form-item>
          <n-form-item label="姓名" path="name">
            <n-input v-model:value="formData.name" placeholder="请输入姓名" />
          </n-form-item>
          <n-form-item label="级别" path="level">
            <n-select
              v-model:value="formData.level"
              :multiple="false"
              :options="[
                { label: '公司级', value: 0 },
                { label: '个人级', value: 1 },
              ]"
              clearable
            />
          </n-form-item>
          <n-form-item label="父节点" path="parentId">
            <n-select
              placeholder="不选择默认根节点"
              v-model:value="formData.parentId"
              :multiple="false"
              :options="parentNodeArr"
              clearable
            />
          </n-form-item>
          <n-form-item label="子任务" path="taskArr">
            <div style="display: flex; flex-direction: column">
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  margin-bottom: 10px;
                "
              >
                <div
                  style="
                    display: flex;
                    justify-content: space-between;
                    margin-right: 10px;
                  "
                >
                  <n-input
                    style="margin-right: 10px"
                    v-model:value="taskObj.title"
                    placeholder="请输入子任务名"
                  />
                  <n-input
                    type="number"
                    v-model:value="taskObj.num"
                    placeholder="请输入子任务进度"
                  />
                </div>
                <n-button type="primary" @click="addTask">新增</n-button>
              </div>
              <div
                style="
                  display: flex;
                  flex-direction: column;
                  max-height: 200px;
                  overflow: auto;
                "
              >
                <div
                  v-for="(item, index) in formData.taskArr"
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-top: 5px;
                  "
                >
                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                      width: 300px;
                      margin-right: 10px;
                      border: 1px solid #f1f1f1;
                      border-radius: 5px;
                      padding: 5px;
                    "
                  >
                    <span>KR{{ index + 1 }}</span>
                    <span style="padding-left: 10px">{{ item.title }}</span>
                    <span>{{ item.num }}%</span>
                  </div>
                  <n-button type="primary" @click="delTask(item.id)"
                    >删除</n-button
                  >
                </div>
              </div>
            </div>
          </n-form-item>
        </n-form>
        <div style="margin-top: 20px; display: flex; justify-content: center">
          <n-button type="primary" @click="addClose" style="margin-left: 10px"
            >取消</n-button
          >
          <n-button type="primary" @click="addOpen" style="margin-left: 10px"
            >确认</n-button
          >
        </div>
      </div>
    </n-modal>
  </div>
</template>

<style lang="scss" scoped></style>
